﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BombController : MonoBehaviour
{
    bool soundflag = false;
    float bombGap = 2f;
    Animator animator;
    Vector3 scale;
    CircleCollider2D bombCollider;
    private Hashtable targetTable;
    AudioSource audio;

    private void Awake()
    {
        audio = GetComponent<AudioSource>();
        animator = gameObject.GetComponent<Animator>();
        bombCollider = gameObject.GetComponent<CircleCollider2D>();
        bombCollider.enabled = false;
        scale = transform.localScale;
        targetTable = new Hashtable();
    }

    // Start is called before the first frame update
    void Start()
    {
    
    }

    // Update is called once per frame
    void Update()
    {
        
        if (bombGap < 0)
        {
            if (!soundflag)
            {
                audio.PlayOneShot(audio.clip);
                soundflag = true;
            }
            animator.SetTrigger("Bomb");            
        }
        else {
            bombGap -= Time.deltaTime;
        }
    }
    

    private void OnBombEnter() {
        scale = new Vector3(0.8f, 0.8f, 0.8f);
        transform.localScale = scale;
        bombCollider.enabled = true;
    }

    private void OnBombExit() {
        hurtTargetTable();
        Destroy(gameObject);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("enter");
        GameObject target = collision.gameObject;        
        targetTable.Add(target.GetHashCode(), target);        
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        Debug.Log("enter");
        GameObject target = collision.gameObject;
        targetTable.Remove(target.GetHashCode());        
    }

    public void hurtTargetTable()
    {
        List<GameObject> tmpList = new List<GameObject>();
        foreach (DictionaryEntry entry in targetTable)
        {
            GameObject target = entry.Value as GameObject;
            tmpList.Add(target);
        }
        Debug.Log(tmpList.Count);
        for (int i = 0; i < tmpList.Count; ++i) {            
            tmpList[i].SendMessage("GetHurt", 50);
            if (tmpList[i].tag == "tree") {
                tmpList[i].GetComponent<FutureTreeController>().StartBurn();
            }
        }
    }

}
